package people.paper.tv.activity.home.modual.ywyl.model.impl;

import android.content.Context;

import com.coocaa.app.support.net.Callback;
import com.coocaa.app.support.net.Result;

import java.util.ArrayList;
import java.util.List;

import people.paper.tv.activity.home.model.MainDataObject;
import people.paper.tv.activity.home.model.MainServerHttpService;
import people.paper.tv.activity.home.modual.ywyl.model.YWYLModel;

public class YWYLModelImpl implements YWYLModel {
    private static class Category {
        public String name;
        public int pageIndex = -1;
        public int current;
        public int total;
    }

    private final List<Category> CATS = new ArrayList<>();

    private int catIndex = 0;

    @Override
    public void create(Context context) {
        String[] cats = new String[]{"DS党报评论", "DS党报头条", "DS换方式", "DS乡村", "DS讲话"};
        for (String cat : cats) {
            Category category = new Category();
            category.name = cat;
            CATS.add(category);
        }
    }

    private boolean bCalling = false;

    @Override
    public void get(int pageIndex, final Callback<Result<List<MainDataObject.YWYLObject>>> callback) {
        synchronized (this) {
            if (bCalling)
                return;
            bCalling = true;
        }
        if (CATS.size() > catIndex) {
            final Category cat = CATS.get(catIndex);
            if (cat.pageIndex == -1) {
                cat.pageIndex = 0;
            } else {
                cat.pageIndex += 1;
            }
            MainServerHttpService.httpService.getPictures(cat.name, cat.pageIndex, new Callback<Result<MainDataObject.YWYLData>>() {
                @Override
                public Ret onResult(Result<MainDataObject.YWYLData> result) {
                    Ret ret = null;
                    if (result.exception != null) {
                        ret = callback.onResult(Result.cc(result, result.data.obj));
                    } else if (result.data.obj != null) {
                        if (cat.pageIndex == 0)
                            cat.total = result.data.total;
                        cat.current += result.data.obj.size();
                        if (cat.current >= cat.total)
                            catIndex += 1;
                        ret = callback.onResult(Result.cc(result, result.data.obj));
                    }
                    if (ret == null)
                        ret = new Ret(0, "");
                    synchronized (YWYLModelImpl.this) {
                        bCalling = false;
                    }
                    return ret;
                }
            });
        } else {
            synchronized (this) {
                bCalling = false;
            }
        }
    }
}
